

var timer_sms_mon = null;

var noc_id = 0;

var closeNocPanel = null;
//无消息自动关闭时间 秒
var nocbox_close_timeout = 3;

$(function () {
   //绑定自由拖动弹出消息框
   var rDrag = {
    o:null,
    init:function(o){
     o.onmousedown = this.start;
    },
    start:function(e){
     var o;
     e = rDrag.fixEvent(e);
                  e.preventDefault && e.preventDefault();
                  rDrag.o = o = this;
     o.x = e.clientX - rDrag.o.offsetLeft;
                   o.y = e.clientY - rDrag.o.offsetTop;
     document.onmousemove = rDrag.move;
     document.onmouseup = rDrag.end;
    },
    move:function(e){
     e = rDrag.fixEvent(e);
     var oLeft,oTop;
     oLeft = e.clientX - rDrag.o.x;
     oTop = e.clientY - rDrag.o.y;
     rDrag.o.style.left = oLeft + 'px';
     rDrag.o.style.top = oTop + 'px';
    },
    end:function(e){
     e = rDrag.fixEvent(e);
     rDrag.o = document.onmousemove = document.onmouseup = null;
    },
       fixEvent: function(e){
           if (!e) {
               e = window.event;
               e.target = e.srcElement;
               e.layerX = e.offsetX;
               e.layerY = e.offsetY;
           }
           return e;
       }
   }
   window.onload = function(){
           var obj = document.getElementById('new_noc_panel');
    rDrag.init(obj);
   }
   
})
  //lp 事务提醒初始化事件
   function initNocbox(){
     
      //绑定打开事务提醒
      var openBtn = $('#nocbox');
      openBtn.live('click',function(){
         var nocboxPanel = $('#new_noc_panel').css("display");
         nocboxPanel == "none" ? noc_mon() : CloseNoc(); 
      });
      
      //按钮绑定关闭事件
      var closeBtn = jQuery('#new_noc_panel > #new_noc_title > span.noc_iterm_close');
      closeBtn.live('click',function(){
         CloseNoc();
      });

     //绑定点击弹出消息框
     var openBtnnoc = jQuery('.openmessagebox');
     openBtnnoc.live('click',function(){
        noc_mon();
        //CloseNoc();
     });
      //内容块hover效果
      var nocBlocks = $('#new_noc_list > div.noc_iterm > ul.noc_iterm_data > li');
      nocBlocks.live('mouseenter', function(){$(this).addClass('noc_iterm_hover');});
      nocBlocks.live('mouseleave', function(){$(this).removeClass('noc_iterm_hover');});
      
      //点击查看提醒
      $('#new_noc_list > div.noc_iterm > ul.noc_iterm_data > li').live('click', function(){
         var url = $(this).attr('url');
         var sms_id = $(this).attr('sms_id');
         var type_id = $(this).attr('type_id');
         RemoveNoc($(this),sms_id, 0);
         //alert(sms_id);
         /*if(url!=""){
            openURL('', '', url, '1');
         }*/
      });
      
      //点击全部已阅
      $('#ViewAllNoc').live('click',function(){
         var idstr = get_noc_idstr();
         //alert(idstr);
         jQuery.ajax({
            async: true,
            url: 'index.php?m=message&a=messageBox', //  messageBox 传值,标记当前用户全部未读信息为0
            data: {'act': 'remove','message_id': idstr},
            cache: false,
            success: function(){
               jQuery('#new_noc_list').empty();
               autocloseNoc();
            },
            error: function(request, textStatus, errorThrown){
               jQuery('#new_noc_list').hide();
               jQuery('#nocbox_tips').html('<div class="error">操作失败(' + request.status + ')：' + textStatus + '</div>').show();
            }
         });
      });
      
      //点击查看详情
      $('#ViewDetail').live('click',function(){
         noc_list();
      });
      
      //点击类型，类型全部已阅
      $('#new_noc_list > div.noc_iterm > .noc_iterm_title > .noc_iterm_read').live('click',function(){
         var idstr = idstr_all = firsturl = "";
         var separator = ",";
         var type_id = $(this).attr('type_id');
         var idstr_all = get_noc_idstr(type_id);
         RemoveNoc($(this),idstr_all, 0);
         var idobj = jQuery("#new_noc_panel > #new_noc_list > .noc_iterm_" + type_id + " > .noc_iterm_data > li");
         idobj.each(function(){
            url = $(this).attr("url");
            sms_id = $(this).attr("sms_id");
            if(url!="" && firsturl==""){
               firsturl = url;
            }
            if(url!=""){
               idstr += separator + jQuery(this).attr("sms_id");
               separator = ",";
            }
         });
        
      });
      
   };
         
      //事务提醒
      initNocbox();


var documentTitle = document.title;
var blinkTitleInterval = null;

//查询消息
function sms_mon()
{
   if(!timer_sms_mon)
       window.clearTimeout(timer_sms_mon);
      
   timer_sms_mon = window.setTimeout(sms_mon, 300000);
   
   jQuery.ajax({
      type: 'GET',
      url: 'index.php?m=User&a=keepOnline', //whh  关闭以后，检测消息，5分钟弹出一次
      dataType: "json",
      //data: {'now': new Date().getTime()},
      success: function(data){
         if(data)
         { 
           // $('new_sms_sound').innerHTML = newSmsSoundHtml;
            if(timer_sms_mon)
            {
               window.clearTimeout(timer_sms_mon);
               timer_sms_mon = null;
            }
            //有新的提醒
            if(data.have_noc >0)
            {
               blinkTitleInterval = window.setInterval(BlinkTitle, 1000);
               noc_mon();

            }
       
           
         }
      }
   });

}

function noc_mon()
{
   var wWidth = (window.document.documentElement.clientWidth || window.document.body.clientWidth || window.innerWidth);
   var wHeight = (window.document.documentElement.clientHeight || window.document.body.clientHeight || window.innerHeight);
   var left = Math.floor((wWidth - jQuery('#new_noc_panel').outerWidth())/2);
   var top  = Math.floor((wHeight - jQuery('#new_noc_panel').outerHeight())/2) - 100;
  
   jQuery('#new_noc_panel').css({left:left, top:top});
  
   //lp 显示事务提醒面板
   jQuery('#new_noc_panel').show().focus();
  
   //lp 触发读取提醒函数
   LoadNoc();
}

// lp 读取提醒数据信息
var newNocArray = [];
function LoadNoc(flag)
{
   jQuery('#nocbox_tips').html('<div class="loading">正在努力的加载……<img src="PUBLIC/vendors/pageloader/images/loader11.GIF" /></div>').show();
   jQuery('#new_noc_list').hide();
   flag = typeof(flag) == "undefined" ? "1" : "0";
   jQuery.ajax({
      type: 'GET',
      url: 'index.php?m=message&a=messageBox', // whh message/messagebox,
      data: {'act':'get_data','FLAG': flag},
      dataType: "json",
      cache: false,
      success: function(data){
         jQuery('#nocbox_tips').empty().hide();
         if(data.data){
            FormatNoc(data);
         }else{
            jQuery("#new_noc_panel > .button").hide();
            jQuery("#new_noc_panel").css("padding-bottom","10px");
            autocloseNoc();
         }
      },
      error: function(request, textStatus, errorThrown){
         jQuery('#nocbox_tips').html('<div class="error">oh ! no ! 努力的加载失败了(' + request.status + ')：' + textStatus + '</div>').show();
      }
   });
}

//lp 格式化提醒数据
function FormatNoc(data)
{
   var html = totalnum ='';
   jQuery('#new_noc_list').empty();
   jQuery.each(data.data,function(key, item){ 
      if(item.is_read == "") return false;     
      //取提醒内容的前2行内容显示
      //var content = decodeURIComponent(item.content);
     var content =item.note;

     var pos = content.indexOf('<br />');
      if(pos >= 0)
      {
         var pos2 = content.indexOf('<br />', pos + 6);
         if(pos2 >= 0)
            content = content.substr(0, pos2);
      }
      
      if(jQuery('#new_noc_list').find('.noc_iterm_'+item.is_read).size()!=0){
         html = '<li id="noc_li_'+item.message_id+'" sms_id="'+item.message_id+'" type_id="'+item.is_read+'"  title="我知道了，点击删除">';
            html += '<p class="noc_iterm_info"><span class="noc_iterm_time">'+decodeURIComponent(item.send_time)+'</span>'+decodeURIComponent(item.from_user_name)+'</p>';
            html += '<p class="noc_iterm_content">'+content+'</p>';
         html += '</li>';
         jQuery('.noc_iterm_'+item.is_read+' > ul').append(html); 
      }else{
         html = '<div class="noc_iterm noc_iterm_'+item.is_read+'">';
         html += '<div class="noc_iterm_title"><span class="noc_iterm_read" type_id="'+item.is_read+'" title="我知道了，点击删除全部"></span>'+decodeURIComponent('站内消息')+'</div>';
         html += '<ul class="noc_iterm_data">';
            html += '<li id="noc_li_'+item.message_id+'" sms_id="'+item.message_id+'" type_id="'+item.is_read+'"  title="我知道了，点击删除">';
               html += '<p class="noc_iterm_info"><span class="noc_iterm_time">'+decodeURIComponent(item.send_time)+'</span>'+decodeURIComponent(item.from_user_name)+'</p>';
               html += '<p class="noc_iterm_content">'+content+'</p>';
            html += '</li>';   
         html += '</ul>';
         html += '</div>';       
         jQuery('#new_noc_list').append(html);
      }
      //alert(html);
   });
   
   var num = get_noc_num();
   
   if(num == 1){
      var _obj = jQuery('#new_noc_list > div.noc_iterm > ul.noc_iterm_data > li');
      /*if(_obj.attr("url")!=""){
      // _obj.click();
       autocloseNoc();
      }*/
   }
   
   //隐藏再show是为了避免出现append的时候，短暂的信息高度变化
   jQuery('#new_noc_list').show(); 
   
   var num = get_noc_num();
   jQuery("#new_noc_panel > #new_noc_title > .noc_iterm_num >span").html(num);
    jQuery("#message_count").html('<b>'+num+'</b>');
    //reloadPage();
   if(num >= 2){
      jQuery('#new_noc_panel').css("padding-bottom","0px");
      jQuery('#new_noc_panel > .button').show();
   }
}

//lp 计算目前有多少条提醒
function get_noc_num(){
   var totalnum = '';
   totalnum = jQuery("#new_noc_panel > #new_noc_list > .noc_iterm > .noc_iterm_data > li").length;
   return totalnum;  
}

//lp 即时计算尚未提醒的提醒
function get_noc_idstr(type_id){
   var idstr = '';
   var separator = '';
   if(type_id!="" && typeof(type_id)!=="undefined")
   {
      var idsobj =jQuery("#new_noc_panel > #new_noc_list > .noc_iterm_" + type_id + " > .noc_iterm_data > li");
   }else
   {
      var idsobj = jQuery("#new_noc_panel > #new_noc_list > .noc_iterm > .noc_iterm_data > li");
   }  
   jQuery.each(idsobj,function(){
      idstr += separator + jQuery(this).attr("sms_id");
      separator = ",";
   });
   return idstr;
}  

function BlinkTitle()
{
   document.title = document.title == "　　　　　　　　" ? "您有新的短消息！" : "　　　　　　　　";
}

function ResetTitle()
{
   window.clearInterval(blinkTitleInterval);
   document.title = documentTitle;
}



function RemoveNoc(obj,recvIdStr, del){
   if(!recvIdStr) return;
   //alert(recvIdStr);
   jQuery.ajax({
      type: 'POST',
      url: 'index.php?m=Message&a=MessageBox', // whh  点击关闭消息
     data: {'act': 'remove','message_id': recvIdStr},
      success: function(data){

            var lis = obj.parents(".noc_iterm").find("ul").find("li").size();
            if(recvIdStr.indexOf(",")!='-1'){
               obj.parents(".noc_iterm").remove()
            }else{
               lis == 1 ? obj.parents(".noc_iterm").remove() : obj.remove();
            }
            var num = get_noc_num();
            jQuery("#new_noc_panel > #new_noc_title > .noc_iterm_num >span").html(num);
            if(num < 2){
               jQuery("#new_noc_panel > .button").hide();
               jQuery("#new_noc_panel").css("padding-bottom","10px");
            }
            autocloseNoc();
      },
      error: function (request, textStatus, errorThrown){
         alert('操作失败：' + textStatus);
      }
   });
}

//lp 如果没有提醒信息，则自动隐藏盒子
function autocloseNoc(){
   var datanum = get_noc_num();
   jQuery("#new_noc_panel > #new_noc_title > .noc_iterm_num >span").html(datanum);
   if(!(datanum > 0)){
      jQuery('#new_noc_list').hide();
      jQuery('#nocbox_tips').html("<h2><b>暂无新提醒</b></h2><br />本窗口 <span class='red'>"+ nocbox_close_timeout +"</span> 秒后自动关闭").show();
      closeNocPanel = window.setInterval(timerclose,1000);  
   }
}

//lp 倒计时
function timerclose(){
   var time = jQuery('#nocbox_tips > span').text();
   if(time > 1){
      jQuery('#nocbox_tips > span').text(time-1);
   }else{
      CloseNoc(); 
   }
}


//关闭窗口，并设置下次检测消息时间
function CloseNoc(){

   jQuery('#new_noc_panel').hide();
   if(!timer_sms_mon)
      timer_sms_mon = window.setTimeout(sms_mon, 300000);
   if(closeNocPanel){
      window.clearInterval(closeNocPanel);
      closeNocPanel = null;
   }
   ResetTitle();  
}

function noc_list()
{
  CloseNoc();
  loadPage('站内消息','index.php?m=message&a=index','0');
}

